package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter")
@Slf4j
public class LoginCheckFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //chain.doFilter(request, response);
        // 把 ServletRequest ServletResponse
        // 强转成处理 http协议的对象
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //1:获取到请求的uri /uri
        String requestURI = request.getRequestURI();

        boolean isAuth = checkAuthUrl(requestURI);

        if (isAuth){
            chain.doFilter(request, response);
            return;
        }

        //判断是不是登录了(手机端)
        // 加一段代码判断前台用户
        // 去 session中找  登录存的哪个 数据
        Long userId = (Long)request.getSession().getAttribute("user");
        if(userId!=null){//登陆过放行
            log.info("已经登录了放行"+requestURI);
            BaseContext.setCurrentId(userId);

            chain.doFilter(request, response);//放行
            return;
        }
        // 判断是否登录了
        Long empId = (Long) request.getSession().getAttribute("employee");
        // 如果这个数据不为null 登陆了 放行
        if (empId!=null){

            BaseContext.setCurrentId(empId);
            chain.doFilter(request, response);
            return;
        }

        R<Object> notlogin = R.error("NOTLOGIN");
        String jsonString = JSON.toJSONString(notlogin);
        response.getWriter().write(jsonString);


    }
    private boolean checkAuthUrl(String requestURI) {
        AntPathMatcher matcher = new AntPathMatcher();
        for (String url : authUrl) {

            if (matcher.match(url,requestURI)){
                return true;
            }

        }
        return false;
    }

    private String[] authUrl = new String[]{
            "/employee/login",
            "/employee/logout",//写不写都行
            "/backend/**", // /backend所有的请求都认定为 白名单
            "/front/**",// /front所有的静态资源 都认定为 白名单
            "/common/**",
            "/user/sendMsg",// 发送验证码
            "/user/login"  // 手机端用户登录
    };
}


